﻿using System.Data;
using System.Data.SqlClient;
using System.Runtime.Serialization;
using K3R.Data;

namespace K3R.Email {
	[DataContract]
	public class EmailTemplate {
		#region Properties
		[DataMember(Name = "id")] public int ID { get; private set; }
		[DataMember(Name = "name")] public string Name { get; private set; }
		[DataMember(Name = "title")] public string Title { get; private set; }
		[DataMember(Name = "body")] public string Body { get; private set; }
		[DataMember(Name = "isHtml")] public bool IsHtml { get; set; }
		#endregion

		#region Constructors
		public EmailTemplate() { }
		#endregion

		#region Static
		public static EmailTemplate Load(int id) {
			EmailTemplate template = null;
			using (Connection conn = new Connection(K3R.Settings.ConnectionString, "EmailTypeLoad")) {
				conn.AddParameter("@ID", id);

				SqlDataReader dr = conn.ExecuteReader(CommandBehavior.SingleRow);
				if (dr.Read())
					template = Reader(dr);
				else throw new EmailNotFoundException();
			}
			return template;
		}

		public static EmailTemplate Load(EmailType id) {
			return Load((int)id);
		}
		#endregion

		#region Conversion
		protected static EmailTemplate Reader(SqlDataReader dr) {
			return new EmailTemplate {
				ID = (int)dr["ID"],
				Name = dr["Name"].ToString(),
				Title = dr["Title"].ToString(),
				Body = dr["Body"].ToString(),
				IsHtml = (bool)dr["IsHtml"]
			};
		}
		#endregion
	}
}
